<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" >
<head>
    <th:block th:include="include :: header('新增传输消息')" />
    <th:block th:include="include :: bootstrap-fileinput-css" />
    <th:block th:include="include :: select2-css" />
</head>
<body class="white-bg">
    <div class="wrapper wrapper-content animated fadeInRight ibox-content">
        <form class="form-horizontal m" id="form-msg-add">
            <div class="col-xs-12">
                <div class="form-group">
                    <label class="col-sm-3 control-label is-required">传输类型：</label>
                    <div class="col-sm-8">
                        <select name="taskType" id="taskType" class="form-control m-b" th:with="type=${@dict.getType('trans_type')}">
                            <option th:each="dict : ${type}" th:text="${dict.dictLabel}" th:value="${dict.dictValue}"></option>
                        </select>
                    </div>
                </div>
            </div>
            <div class="col-xs-12">
                <div class="form-group">
                    <label class="col-sm-3 control-label is-required">接收对象：</label>
                    <div class="col-sm-8">
                        <div id="selectObjsAttr" class="row">
                            <div class="col-sm-12">
                                <select name="selectObjs" id="selectObjs" class="form-control select2-multiple" multiple>
                                </select>
                            </div>
                        </div>
                        <div id="multicastAttr" class="row hidden">
                            <div class="col-sm-6">
                                <input name="multicastAddr" id="multicastAddr" class="form-control" placeholder="请输入地址" type="text">
                            </div>
                            <div class="col-sm-6">
                                <input name="multicastPort" id="multicastPort" class="form-control" placeholder="请输入端口" type="text">
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="col-xs-12">
                <div class="form-group">
                    <label class="col-sm-3 control-label">消息数据：</label>
                    <div class="col-sm-8">
                        <textarea name="msgData" id="msgData" class="form-control" placeholder="请输入消息内容（长度不超过1024字节）"></textarea>
                    </div>
                </div>
            </div>
            <div class="col-xs-12">
                <div class="form-group">
                    <label class="col-sm-3 control-label">文件信息：</label>
                    <div class="col-sm-8">
                        <div class="file-loading">
                            <input id="multipleFile" name="files" type="file" multiple>
                        </div>
                    </div>
                </div>
            </div>
        </form>
    </div>
    <th:block th:include="include :: footer" />
    <th:block th:include="include :: jquery-cxselect-js" />
    <th:block th:include="include :: select2-js" />
    <th:block th:include="include :: bootstrap-fileinput-js" />
    <script th:inline="javascript">
        var prefix = ctx + "transmission/msg";

        var filesMap = new Map();

        $("#form-msg-add").validate({
            focusCleanup: true
        });

        function loadSelectData(obj, data) {
            var dataHtml = "";
            for(index in data) {
                var tmp = data[index];
                dataHtml +='<optgroup label="&#45;&#45;' + tmp.n + '&#45;&#45;">';
                for ( i in tmp.s){
                    var stmp = tmp.s[i];
                    dataHtml +='<option value="'+ stmp.v +'">' + stmp.n + '</option>';
                }
            }
            $(obj).html(dataHtml);
        }

        function submitHandler() {
            if ($.validate.form()) {
                var taskType = $('#taskType').val();
                var receivers;
                var recvAddr = $('#multicastAddr').val();
                var recvPort = $('#multicastPort').val();
                if(taskType == 0 || taskType == 3) {
                    receivers = $('#selectObjs').val().join(':');
                    if(!receivers) {
                        alert('请选择接收对象');
                        return false;
                    }
                } else {
                    if(!recvAddr || !recvPort) {
                        alert('请填写地址和端口');
                        return false;
                    }
                }
                var msgData = $('#msgData').val();
                var msgFiles = [];
                if(recvPort == null || recvPort == "") {
                    recvPort = 0;
                }

                for (const [key, value] of filesMap) {
                    msgFiles.push(value);
                }
                // $('.file-preview-success').each(function(){
                //     msgFiles.push($(this).attr('id'));
                // });
                if(!msgData && msgFiles.length == 0) {
                    alert('请填写消息内容或上传文件');
                    return false;
                }
                msgFiles = msgFiles.join(':');

                var data = [];
                data.push({"name": "taskType", "value": taskType});
                data.push({"name": "receivers", "value": receivers});
                data.push({"name": "msgData", "value": msgData});
                data.push({"name": "msgFiles", "value": msgFiles});
                data.push({"name": "recvAddr", "value": recvAddr});
                data.push({"name": "recvPort", "value": recvPort});

                $.operate.save(prefix + "/addSave", data);
            }
        }
        // 直接返回获取
        var data = [[${data}]];

        loadSelectData("#selectObjs", data);

        $('#element').cxSelect({
            selects: ['type', 'router'],
            jsonValue: 'v',
            data: data
        });

        // 文件上传
        $("#multipleFile").fileinput({
            uploadUrl: ctx + 'common/uploads',
            uploadAsync: false
        }).on('fileuploaded', function(event, data, previewId, index){
            var rsp = data.response;
            filesMap.set(previewId, rsp.fileName);

            log.info("reutrn fileNames：" + rsp.url);
            log.info("reutrn fileNames：" + rsp.fileName);
        }).on('filebatchuploadsuccess', function (event, data, previewId, index) {
            var rsp = data.response;
            var fileNameArr = rsp.fileNames.split(",");
            for(var i = 0 ; i < previewId.length; i++) {
                if(fileNameArr[i]) {
                    filesMap.set(previewId[i], fileNameArr[i]);
                }
            }
            // filesArr.push(rsp.fileNames.split(","));
            log.info("return urls：" + rsp.urls)
            log.info("reutrn fileNames：" + rsp.fileNames)
            log.info("reutrn newFileNames：" + rsp.newFileNames)
            log.info("return originalFilenames：" + rsp.originalFilenames)
        }).on('filebatchuploadcomplete', function(event, files, extra){
            $('.file-preview-success').each(function(){
               log.info("id:" + $(this).attr('id'));
            });
            log.info("return urls：" + files);
        }).on('fileremoved', function (event, id, index) {
            $("input[name='" + event.currentTarget.id + "']").val('');
            log.info("fileremoved previewId:" + id);
        }).on('filesuccessremove', function (event, data, previewId, index) {
            log.info("remove previewId:" + previewId);
            filesMap.delete(previewId);
        });


        $('#taskType').on('select2:select', function (e) {
            // 处理自己的业务
            var item = $('#taskType').select2('val');
            if(item == 1 || item == 2) {
                $('#selectObjsAttr').attr('class','row hidden');
                $('#multicastAttr').attr('class','row');
            } else {
                $('#selectObjsAttr').attr('class','row');
                $('#multicastAttr').attr('class','row hidden');
            }
        });
    </script>
</body>
</html>